package com.cxs.xiaomi.utils;

import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/*
 * @Author:cxs
 * @Date:2021/9/14  17:12
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
public class ValidateCodeUtil {
    // 验证码源码
    private static final String STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static Random random = new Random();

    /**
     * 验证码生成类
     * @param session 会话作用域
     * @param codeKey 保存code的key
     * @param num 验证码位数
     * @return
     */
    public static BufferedImage getCodeImage(HttpSession session,String codeKey,int num){
        int width = 120;
        int height = 30;
        BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_BGR);
        Graphics pen = image.getGraphics();
        pen.fillRect(0, 0, width, height);
        pen.setFont(new Font("微软雅黑", Font.BOLD, 20));
        String code = getCode(num);
        session.setAttribute(codeKey, code);
        for (int i = 0; i < code.length(); i++) {
            pen.setColor(getColor());
            pen.drawString(String.valueOf(code.charAt(i)), i * 15 + 25, 25);
        }
        return image;
    }


    /**
     * 获得指定位数字符串
     * @param size
     * @return
     */
    private static String getCode(int size) {
        String str = "";
        for (int i = 0; i < size; i++) {
            str += STR.charAt(random.nextInt(STR.length()));
        }
        return str;
    }

    // 随机获得颜色
    private static Color getColor() {
        int red = random.nextInt(256);
        int green = random.nextInt(256);
        int blue = random.nextInt(256);
        return new Color(red, green, blue);
    }
}
